<template>
  <div class="home bg-fff">
    <div class="navs flex bg-theme">
      <el-button-group>
        <el-button :type="solarCurr===index?'primary':''" v-for="(item,index) in tableList" :key="index" @click="changeSolar(index)">{{item.title}}</el-button>
      </el-button-group>
    </div>
    <div class="page bg-fff" id="capture-all">
      <div class="content flex" v-if="tableList.length>0">
        <div class="top-10 bottom-10 left-20" :id="'capture-'+plate.building" v-for="(plate, plateIndex) in tableList[solarCurr].list" :key="plateIndex">
          <div class="averageRow font25 flex text-center fontBold">
            <div class="averageTit">整列均价</div>
            <div class="unitItem flex" v-for="(unitItem, unitI) in plate.unit_list" :key="'unit-'+unitI">
              <div class="averageVal" :class="plate.unit_list.length > 1 && unitItem.max_room > 1?'moreColSty':'onlyColSty'" v-for="(unitColumnItem, columnI) in unitItem.columnPrices" :key="'column-'+columnI">
                {{ unitColumnItem | averageByArr }}<span class="font12">元/m²</span>
              </div>
            </div>
          </div>
          <div class="tableBox flex">
            <div class="floorBox border-top-theme border-bottom-theme border-left-theme border-right-theme">
              <div class="headFloor text-center">
                <div class="floorType bg-theme"></div>
                <div class="floorType">实际</div>
              </div>
              <div class="floor flex" v-for="(floorItem, index) in plate.unit_list[0].floorList" :key="index">
                <span class="fontBold font15">{{ floorItem.floorShiji }}</span>
                <div class="top-3">层</div>
              </div>
            </div>
            <div class="floorBox border-top-theme border-bottom-theme border-right-theme">
              <div class="headFloor text-center">
                <div class="floorType bg-theme"></div>
                <div class="floorType">名义</div>
              </div>
              <div class="floor flex" v-for="(floorItem, index) in plate.unit_list[0].floorList" :key="index">
                <span class="fontBold font15">{{ floorItem.floor }}</span>
                <div class="top-3">层</div>
              </div>
            </div>
            <div class="tableScroll" v-for="(unitItem, unitIndex) in plate.unit_list" :key="unitIndex">
              <div class="headLineBox">
                <div class="unit font23 bg-theme col-fff fontBold text-center">{{unitItem.unit?unitItem.unit+'号':''}}</div>
                <div class="roomList" v-for="(roomItem, roomIndex) in unitItem.rooms" :key="roomIndex">
                  <div class="roomItem flex fontBold" :class="plate.unit_list.length > 1 && unitItem.max_room > 1?'moreColSty':'onlyColSty'">0{{roomItem}}室</div>
                </div>
              </div>
              <div class="floorsBox" v-for="(floorItem, floorIndex) in unitItem.floorList" :key="floorIndex">
                <div class="roomBox" v-for="(roomItem, roomIndex) in floorItem.house_list" :key="roomIndex">
                  <div v-if="roomItem.size || roomItem.price">
                    <div class="room bg-error-opacity text-center" :class="plate.unit_list.length > 1 && unitItem.max_room > 1?'moreColSty':'onlyColSty'">
                      <div class="col-bf7c03 top-10">{{roomItem.size}}m²</div>
                      <div class="top-5 fontBold font16 amount"><span class="font12">总价</span>{{roomItem.amount}}万</div>
                      <div class="top-5 fontBold font16">{{roomItem.price}}<span class="font12">元/m²</span></div>
                      <div class="flex top-5" v-if="roomItem.priceDiff != 0">
                        <div class="flex" v-if="roomItem.diffPrice > 0">
                          <span class="iconArrow bg iconArrowUp right-5"></span>
                          {{roomItem.diffPrice}}
                        </div>
                        <div class="flex" v-if="roomItem.diffPrice < 0">
                          <span class="iconArrow bg iconArrowDown right-5"></span>
                          {{roomItem.diffPrice}}
                        </div>
                      </div>
                      <div v-if="roomItem.sun_min > 0">
                        <div class="sunBox flex col-fff" :class="{'bg-5195B7': roomItem.sun_min <=1, 'bg-7DAA49': roomItem.sun_min > 1 && roomItem.sun_min <=2, 'bg-C7CC09': roomItem.sun_min > 2 && roomItem.sun_min <=2.5 && showCol2, 'bg-ffa600': roomItem.sun_min > 2.5 && roomItem.sun_min<=3, 'bg-ff6200': roomItem.sun_min > 3 && roomItem.sun_min <=4, 'bg-f6002d': roomItem.sun_min > 4 && roomItem.sun_min<=5, 'bg-A80000': roomItem.sun_min>5}">
                          <img class="iconSun" src="../assets/icon-sun.png" alt="" srcset="">
                          <div class="sunTime flex">
                            <div class="font12">日照</div>
                            <span class="fontBold left-3">{{roomItem.sun_min?roomItem.sun_min:''}}</span>
                          </div>
                        </div>
                      </div>
                      <div class="top-5" v-if="roomItem.comment">{{roomItem.comment}}</div>
                    </div>
                  </div>
                  <div class="room bg-error-opacity" :class="plate.unit_list.length > 1 && unitItem.max_room > 1?'moreColSty':'onlyColSty'" v-else></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <p class="font13 left-40 top-20">以上智慧选房一房一价和日照测算由小胖君专业团队根据公示规划图纸测算，仅供参考以实际交房为准。</p>
    </div>


    <!-- <img style="width:100%" :src="watermarkImgUrl" alt=""> -->

    <div class="saveBtn">
      <el-button class="btn" round @click="downLoadImage">
        <div class="flex">
          <span class="longPress"></span>点击保存图片
          <img class="saveImg" :src="imgUrl" v-if="imgUrl" />
        </div>
      </el-button>
    </div>
    <canvas id="imgCanvas" class="imgCanvas"></canvas>
    <div class="zhanwei"></div>
  </div>
</template>

<script>
// @ is an alias to /src
import wx from "weixin-js-sdk";
import html2canvas from "html2canvas";
import { initWXSDK, kaiPanAPI, oneHousePriceAPI } from "@/api/api";
import { getHashValue } from "@/common/common";
import { setToken, getToken } from "@/utils/auth";

export default {
  name: "CalendarKai",
  data() {
    return {
      solarCurr: 0,
      colorList: [{
        hours: 1,
        color: '#5195B7'
      },{
        hours: 2,
        color: '#7DAA49'
      },{
        hours: 3,
        color: '#ffa600'
      },{
        hours: 4,
        color: '#ff6200'
      },{
        hours: 5,
        color: '#f6002d'
      },{
        hours: 6,
        color: '#A80000'
      }],
      showCol2: false,
      houseTypeList: [],
      imgUrl: "",
      token: "",
      cityCode: "310100",
      curr: 0,
      tableList: [],
      catchList: [],
      productId: null,
      kaiId: null,
      title: '',
      zhuangXiu: '',
      watermarkImgUrl: ''
    };
  },
  filters: {
    averageByArr(arr) {
      if(arr.length === 0) return '--';
      return Math.round(arr.reduce((a,b) => parseInt(a) + parseInt(b)) / arr.length);
    }
  },

  mounted() {
    //debug true 
    // let token = getHashValue('token') || 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3NDUzODc2ODgsImlhdCI6MTc0NDc4Mjg4OCwiaXNzIjoiIiwiZGF0YSI6eyJ1c2VyX2lkIjo4NDQ3Nn19.X74s9QcMSOSZ0u5XvtQgKP9R9gGOiI6H7goWd25NdC4';
    // this.token = token;
    // setToken(token);
    // this.$store.commit("setToken", token);
    // this.cityCode = 310100;
    // this.productId = 2330;
    // this.kaiId = 5582;

    //debug false
    let token = getHashValue("token");
    this.token = token;
    setToken(token);
    this.$store.commit("setToken", token);
    this.cityCode = getHashValue("cityCode");
    this.productId = getHashValue("productId");
    this.kaiId = getHashValue("kaiId");

    //天汇世纪玺添加2.5小时日照
    if(this.cityCode == '310100' && this.productId == 1166) {
      this.colorList.splice(2,0,{
        hours: 2.5,
        color: '#C7CC09'
      })
      this.showCol2 = true
    }

    this.init();

    // console.log("cityCode:"+this.cityCode)
    // console.log("productId:"+this.productId)
    // console.log("kaiId:"+this.kaiId)
  },
  
  methods: {
    //请求数据
    async requestData() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0)",
      });
      await oneHousePriceAPI(this.kaiId).then((res) => {
        let { price, list } = res.detail;
        if(price.length) {
          this.houseTypeList = price;
        }
        let copyArr = list;
        if(copyArr.length > 0) {
          //循环楼栋
          copyArr.forEach((solarItem, solarIndex) => {
            solarItem.buildingList = [{type: 'all', name: '全部'}];
            solarItem.list.forEach((building, buildingIndex) => {
              //设置楼栋nav
              solarItem.buildingList.push({
                type: building.building,
                name: building.building+'栋'
              })
              if(building.unit_list.length > 0) {
                let allUnitFloors = [];
                building.unitFloorsArrObj = [];//给所有楼栋设置总楼层属性
                building.buildingTypes = {};//给所有楼栋设置类型和单价

                //循环单元
                building.unit_list.forEach((unit, unitIndex) => {
                  if(unit.floor_list.length > 0) {
                    unit.rooms = [];//设置单元的房号
                    unit.columnPrices = [];//单元内每一列价格的组合
                    //循环楼层
                    for(let floor = 0; floor < unit.floor_list.length; floor++) {
                      //所有单元的楼层交集
                      allUnitFloors.push(unit.floor_list[floor]);

                      let hash = {};
                      //集合所有单元楼层,floor去重
                      building.unitFloorsArrObj = allUnitFloors.reduce((pre, cur) => {
                        hash[cur.floor] ? '':hash[cur.floor] = true && pre.push(cur);
                        return pre
                      }, []);
                      //再降序排序
                      building.unitFloorsArrObj.sort(function(a, b) {return b.floor - a.floor});

                      const maxRoom = unit.max_room;

                      // 找到完整的楼层数据
                      const completeFloor = unit.floor_list.find(floor => 
                        floor.house_list.length === maxRoom
                      );

                      // 设置默认房间号
                      unit.rooms = Array.from({length: maxRoom}, (_, i) => 
                        unit.left ? i + 1 : maxRoom - i
                      );

                      // 如果存在完整的楼层数据，则使用完整的楼层数据
                      if (completeFloor) {
                        unit.rooms = completeFloor.house_list.map((_, i) => 
                          completeFloor.house_list[i].room
                        );
                      }
                    }
                  }
                })

                //循环单元修改数据
                building.unit_list.forEach((unit, unitIndex) => {
                  let maxRoomArr = [];//单元内最大的房间数量

                  //也可通过rooms去检索房间号
                  for(let maxItem = 0; maxItem < unit.rooms.length; maxItem++) {
                    unit.columnPrices.push([]);
                    maxRoomArr.push({
                      amount: '',
                      max_sun: 0,
                      min_sun: 0,
                      price: '',
                      room: unit.rooms[maxItem],
                      size: '',
                      diffPrice: 0
                    })
                  }

                  unit.floorList = [];

                  for(let floorI = 0; floorI < building.unitFloorsArrObj.length; floorI++) {
                    //原理就是先把数组转换成字符串再转换成对象 ,这样会新分配一块内存新创建一个对象
                    unit.floorList.push(JSON.parse(JSON.stringify({
                      floor: building.unitFloorsArrObj[floorI].floor,
                      floorShiji: building.unitFloorsArrObj[floorI].floor_123,
                      house_list: maxRoomArr
                    })))
                  }
                  
                  //循环最高楼层
                  for(let floorI = 0; floorI < unit.floorList.length; floorI++) {
                    if(unit.floor_list.length > 0) {
                      //循环实际楼层
                      for(let floor = 0; floor < unit.floor_list.length; floor++) {
                        //找到相同的楼层
                        if(unit.floorList[floorI].floor === unit.floor_list[floor].floor) {
                          unit.floorList[floorI].floorShiji = unit.floor_list[floor].floor_123;
                          if(unit.floor_list[floor].house_list.length > 0) {
                            for(let room =0; room < unit.floor_list[floor].house_list.length; room++) {
                              for(let roomI = 0; roomI < unit.floorList[floorI].house_list.length; roomI++) {
                                //找到相同的房间,赋值更新floorList
                                if(unit.floor_list[floor].house_list[room].room === unit.floorList[floorI].house_list[roomI].room) {
                                  unit.floorList[floorI].house_list[roomI] = unit.floor_list[floor].house_list[room];
                                  if(unit.floor_list[floor].house_list[room].price) {
                                    unit.columnPrices[roomI].push(unit.floor_list[floor].house_list[room].price)
                                  }
                                  //计算单价涨幅
                                  if(this.houseTypeList.length > 0) {
                                    this.houseTypeList.forEach(item => {
                                      if(item.value === unit.floor_list[floor].house_list[room].type) {
                                        building.type = building.building;
                                        building.name = building.building+'栋';
                                        building.buildingTypes[item.value] = item;
                                        unit.floorList[floorI].house_list[roomI].diffPrice = (unit.floor_list[floor].house_list[room].price - item.price).toFixed(1)
                                      }
                                    })
                                  }
                                }
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                })
              }
            })
          })
          this.catchList = copyArr;
          this.changeSolar();
        }
        loading.close();
      });
    },

    //切换节气
    changeSolar(index=0) {
      this.solarCurr = index;
      this.bindFloorHouse();
    },

    //根据楼栋单元筛选一房一价
    bindFloorHouse(){
      if(this.catchList[this.solarCurr].buildingList[this.curr].type === 'all') {
        this.tableList = JSON.parse(JSON.stringify(this.catchList));
      }else {
        let currBuilding = this.catchList[this.solarCurr].list.filter(item => {
          return item.building === this.catchList[this.solarCurr].buildingList[this.curr].type
        })
        this.tableList[this.solarCurr].list = currBuilding;
      }
    },

    //绘制canvas
    async canvasDraw() {
      let buildings = this.tableList[this.solarCurr].list.map(item => item.building);
      // buildings.unshift('all');
      for(let index=0; index < buildings.length; index++) {
        const documentIdEl = document.getElementById(`capture-${buildings[index]}`);
        let docHeight = documentIdEl.offsetHeight;
        let resImgData = await html2canvas(document.querySelector(`#capture-${buildings[index]}`), {
          scale: docHeight > 18000 ? 0.5 : docHeight > 9000 ? 1 : 2,//超过浏览器最大高度限制,缩小倍数,防止出现空白
          // scale: this.curr === 0 ? 1 : 2,//超过浏览器最大高度限制,缩小倍数,防止出现空白
          useCORS: true,
          width: documentIdEl.offsetWidth,
          height: docHeight + 5,
          windowWidth: document.body.scrollWidth,
          windowHeight: document.body.scrollHeight,
          // x: 0,
          // y: 160,
        });

        this.imgUrl = resImgData.toDataURL("image/png", 1);
        
        await this.drawWatermark({
          url: this.imgUrl,
          building: buildings[index]
        });
      }
    },

    //给生成的图片添加水印
    async drawWatermark({
      url = '',
      building = 0,
      textAlign = 'left',
      textBaseLine = 'top',
      font = '40px Microsoft yahei',
      fillStyle = 'rgba(0,0,0,0.1)',
      content = '小胖看房团'
    }={}) {
      return new Promise((resolve) => {
        const that = this;
        const img = new Image();
        img.src = url;
        img.crossOrigin = 'anonymous';
        img.onload = function(){
          //绘制图片到canvas
          const imgCanvas = document.getElementById('imgCanvas');
          imgCanvas.width = img.width;
          imgCanvas.height = img.height;
          const ctx = imgCanvas.getContext('2d');
          ctx.drawImage(img, 0, 0);
          ctx.textAlign = textAlign;
          ctx.textBaseline = textBaseLine;
          ctx.font = font;
          ctx.fillStyle = fillStyle;
          ctx.rotate((Math.PI / 180) * 15);
          //循环绘制水印
          for(let i=0; i < img.height / 120; i++) {
            for(let j = 2; j < img.width; j++) {
              ctx.fillText(content, i*400, j*400, img.width)
            }
          }
          //会直接输转换为base64
          let watermarkImgUrl = imgCanvas.toDataURL();
          let alink = document.createElement("a");
          alink.href = watermarkImgUrl;
          const picName = `${that.title}_${that.tableList[that.solarCurr].title}_${that.productId}_${that.kaiId}_${building}_average`;//图片名
          alink.download = picName;
          alink.click();
          resolve(picName);
        }
      })
    },

    //初始化，请求开盘信息和一房一价数据
    init() {
      kaiPanAPI(this.kaiId).then(res => {
        if(res.status === 0) {
          let { pan } = res.detail;
          this.title = pan.title;
          this.zhuangXiu = pan.xiu;
          this.requestData();
        }else {
          this.$message.error("网络错误，请稍后重试");
        }
      })

      let url = window.location.href;
      // let url = location.href.split("#")[0];
      initWXSDK(url).then((res) => {
        let details = res.detail;
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: details.appId, // 必填，公众号的唯一标识
          timestamp: details.timestamp, // 必填，生成签名的时间戳
          nonceStr: details.nonceStr, // 必填，生成签名的随机串
          signature: details.signature, // 必填，签名
          jsApiList: [], // 必填，需要使用的JS接口列表
        });
        wx.ready(function () {});
        wx.error(function (err) {});
      });
    },

    //点击下载图片
    async downLoadImage(){
      const loading = this.$loading({
        lock: true,
        text: "下载中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, .5)",
      });
      try {
        await this.canvasDraw();
      } catch (error) {
        console.log(error)
      }
      loading.close();
    },

    //跳转小程序
    toXCXHouse(info) {
      var ua = window.navigator.userAgent.toLowerCase();
      //先判断是否微信浏览器
      if (ua.match(/MicroMessenger/i) == "micromessenger") {
        //再判断一下是否在小程序里
        wx.miniProgram.getEnv((res) => {
          if (res.miniprogram) {
            wx.miniProgram.navigateTo({
              url: `/pages/house/detail?id=${info.id}`,
              success: function () {},
              fail: function () {},
              complete: function () {
              },
            });
          }
        });
      }
    },
  },
};
</script>
<style scoped lang="less">
.moreColSty{
  width: 120px;
}
.onlyColSty{
  width: 240px;
}
.home {
  min-height: 100vh;
  overflow: hidden;
  .navs{
    height: 80px;
    justify-content: flex-start;
    padding-left: 20px;
  }
  .iconArrowDown{
    background-image: url("../assets/icon-arrow-down-primary.png");
  }
  .iconArrowUp{
    background-image: url("../assets/icon-arrow-up-error.png");
  }
  .page {
    line-height: 1;
    .content{
      justify-content: flex-start;
      align-items: flex-start;
      flex-wrap: wrap;
    }
    .averageRow{
      height: 35px;
      line-height: 35px;
      justify-content: flex-start;
      align-items: flex-start;
      border: 1px solid #faa000;
      .averageTit{
        width: 120px;
      }
      .averageVal{
        border-left: 1px solid #faa000;
      }
    }
    .tableBox {
      justify-content: flex-start;
      align-items: flex-start;
      .headFloor{
        height: 70px;
        .floorType{
          height: 35px;
          line-height: 35px;
        }
      }
      .floorBox {
        width: 60px;
        .floor {
          height: 140px;
          flex-direction: column;
          border-top: 1px solid #faa000;
        }
      }
      .tableScroll {
        min-height: 100px;
        border-bottom: 1px solid #faa000;
        border-top: 1px solid #faa000;
        .headLineBox{
          .unit{
            height: 35px;
            line-height: 35px;
          }
          .roomList{
            display: inline-block;
            .roomItem{
              height: 35px;
              line-height: 35rpx;
              overflow: hidden;
              border-right: 1px solid #faa000;
            }
          }
          .houseNum{
            width: 120px;
            height: 35px;
            line-height: 35px;
            display: inline-block;
            border-right: 1px solid #faa000;
          }
        }
        .floorsBox {
          height: 140px;
          text-align: left;
          border-top: 1px solid #faa000;
          .roomBox {
            display: inline-block;
            .room {
              height: 140px;
              overflow: hidden;
              border-right: 1px solid #faa000;
              .sunBox{
                border-radius: 15px;
                margin-left: 15px;
                margin-right: 15px;
                margin-top: 5px;
                .iconSun{
                  height: 20px;
                }
                .sunTime{
                  line-height: 1.4;
                  justify-content: flex-start;
                }
              }
              .iconArrow{
                display: inline-block;
                width: 10px;
                height: 16px;
              }
            }
          }
        }
      }
    }
  }
  .imgCanvas{
    opacity: 0;
    position: fixed;
    left: -99999;
  }
  .zhanwei{
    height: 100px;
  }
  .saveBtn {
    position: fixed;
    bottom: 30px;
    left: 0;
    width: 100%;
    z-index: 9;
    text-align: center;
    .btn {
      width: 92%;
      max-width: 400px;
      border-color: #ff8700;
      background: #ff8700;
      color: #fff;
      position: relative;
      .longPress {
        width: 18px;
        height: 18px;
        background-image: url("../assets/icon-long-press.png");
        background-repeat: no-repeat;
        background-size: cover;
        background-position: center;
        display: inline-block;
        margin-right: 5px;
      }
      .saveImg {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 10;
        width: 100%;
        opacity: 0;
      }
    }
  }
}
</style>